package org.budo.mongo.jdbc.driver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.budo.jdbc.driver.AbstractBudoJdbcDriver;
import org.budo.jdbc.driver.exception.BudoJdbcDriverNotSupportedException;
import org.budo.jdbc.driver.parser.SqlStatementParser;
import org.budo.jdbc.driver.parser.cache.CachedJdbcStatementParser;
import org.budo.mongo.jdbc.driver.parser.jsqlparser.JSqlParserMongoStatementParser;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;

/**
 * @author li
 */
public class BudoMongoJdbcDriver extends AbstractBudoJdbcDriver {
    private static final SqlStatementParser DEFAULT_STATEMENT_PARSER = new CachedJdbcStatementParser().statementParser(new JSqlParserMongoStatementParser());

    static {
        try {
            DriverManager.registerDriver(new BudoMongoJdbcDriver());
        } catch (SQLException e) {
            throw new RuntimeException("Can't register driver!", e);
        }
    }

    @Override
    public boolean acceptsURL(String url) throws SQLException {
        return url.startsWith("mongodb://");
    }

    /**
     * @param url "mongodb://user:password@localhost:27017/mydb"
     */
    @SuppressWarnings("resource")
    public Connection connect(String url, Properties info) throws SQLException {
        if (null == url || url.isEmpty()) {
            throw new BudoJdbcDriverNotSupportedException("url can not be null, url=" + url + ", info=" + info);
        }

        MongoClientURI mongoClientUri = new MongoClientURI(url);

        MongoClient mongoClient = new MongoClient(mongoClientUri);
        MongoDatabase mongoDatabase = mongoClient.getDatabase(mongoClientUri.getDatabase());

        return new BudoMongoJdbcConnection() //
                .mongoClient(mongoClient) //
                .mongoDatabase(mongoDatabase) //
                .statementParser(DEFAULT_STATEMENT_PARSER) //
                .url(url); //
    }
}